package org.jetbrains.plugins.scala.compiler

import org.jetbrains.plugins.scala.compiler.CompilerMessagesUtil.{assertCompilingScalaSources, assertNoErrorsOrWarnings}
import org.jetbrains.plugins.scala.compiler.data.IncrementalityType
import org.jetbrains.plugins.scala.{CompilationTests_Zinc, ScalaVersion}
import org.junit.Assert.assertTrue
import org.junit.experimental.categories.Category

import java.nio.file.Files
import scala.jdk.CollectionConverters._

@Category(Array(classOf[CompilationTests_Zinc]))
class MultipleClassesInOneFileTest extends ScalaCompilerTestBase with JdkVersionDiscovery {

  override protected def supportedIn(version: ScalaVersion): Boolean = version == ScalaVersion.Latest.Scala_2_13

  override protected val incrementalityType: IncrementalityType = IncrementalityType.SBT

  def testRemoveOneClassFileAndCompileAgain(): Unit = {
    addFileToProjectSources("foo.scala",
      """class Foo
        |class Bar
        |class Baz
        |""".stripMargin)

    val messages1 = compiler.make().asScala.toSeq
    assertNoErrorsOrWarnings(messages1)
    assertCompilingScalaSources(messages1, 1)

    val classFileNames = List("Foo", "Bar", "Baz")

    val firstClassFiles = classFileNames.map(findClassFile)
    val firstTimestamps = firstClassFiles.map(Files.getLastModifiedTime(_).toMillis)

    removeFile(firstClassFiles(1)) // remove Bar.class

    val messages2 = compiler.make().asScala.toSeq
    assertNoErrorsOrWarnings(messages2)
    assertCompilingScalaSources(messages2, 1)

    val secondClassFiles = classFileNames.map(findClassFile)
    val secondTimestamps = secondClassFiles.map(Files.getLastModifiedTime(_).toMillis)

    val recompiled = firstTimestamps.zip(secondTimestamps).forall { case (x, y) => x < y }
    assertTrue("Not all source files were recompiled", recompiled)
  }
}
